ParametrizeCamera_FileAccess.py

Import File(s) to / Export File(s) from Camera(s)

It shows how to import file(s) to / export file(s) from camera(s), and get file access progress. The major steps include reading a file (such as UserSet1.bin) from camera by calling MV_CC_FileAccessRead(), writing a file (such as UserSet1.bin) to camera by calling MV_CC_FileAccessWrite(), and getting the progress of file access by calling MV_CC_GetFileAccessProgress().

1 # -- coding: utf-8 --
2 
3 import time
4 import sys
5 import threading
6 import platform
7 import os
8 from ctypes import *
9 
10 # Compatible with different operating systems to load DDL
11 currentsystem = platform.system()
12 if currentsystem == 'Windows':
13  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
14 else:
15  sys.path.append(os.path.join("..", "..", "MvImport"))
16 from MvCameraControl_class import *
17 
18 # Compatible with input processing of Python 2.X and 3.X
19 if sys.version_info[0] < 3:
20  # Python 2.x
21  input_func = raw_input
22 else:
23  # Python 3.x
24  input_func = input
25 
26 # Decoding Characters
27 def decoding_char(ctypes_char_array):
28  """
29  Safely decode a string from a ctypes character array.
30  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
31  """
32  byte_str = memoryview(ctypes_char_array).tobytes()
33 
34  # Truncate at the first null character
35  null_index = byte_str.find(b'\x00')
36  if null_index != -1:
37  byte_str = byte_str[:null_index]
38 
39  # Attempt to decode using multiple encodings
40  for encoding in ['gbk', 'utf-8', 'latin-1']:
41  try:
42  return byte_str.decode(encoding)
43  except UnicodeDecodeError:
44  continue
45 
46  # If all encodings fail, use a replacement strategy
47  return byte_str.decode('latin-1', errors='replace')
48 
49 
50 # Define a function for ProgressThread
51 def progress_thread(cam=0, nMode=0):
52  stFileAccessProgress = MV_CC_FILE_ACCESS_PROGRESS()
53  memset(byref(stFileAccessProgress), 0, sizeof(stFileAccessProgress))
54  while True:
55  # Get the progress of file access
56  ret = cam.MV_CC_GetFileAccessProgress(stFileAccessProgress)
57  print ("State = [%x],Completed = [%d],Total = [%d]" % (ret, stFileAccessProgress.nCompleted, stFileAccessProgress.nTotal))
58  if (ret != MV_OK or (stFileAccessProgress.nCompleted != 0 and stFileAccessProgress.nCompleted == stFileAccessProgress.nTotal)):
59  print('press Enter key to continue.')
60  break
61 
62 # Define a function for FileAccessThread
63 def file_access_thread(cam=0, nMode=0):
64  stFileAccess = MV_CC_FILE_ACCESS()
65  memset(byref(stFileAccess), 0, sizeof(stFileAccess))
66  stFileAccess.pUserFileName = 'UserSet1.bin'.encode('ascii')
67  stFileAccess.pDevFileName = 'UserSet1'.encode('ascii')
68  if 1 == nMode:
69  # Read mode
70  ret = cam.MV_CC_FileAccessRead(stFileAccess)
71  if MV_OK != ret:
72  print ("file access read fail ret [0x%x]\n" % ret)
73  elif 2 == nMode:
74  # Write mode
75  ret = cam.MV_CC_FileAccessWrite(stFileAccess)
76  if MV_OK != ret:
77  print ("file access write fail ret [0x%x]\n" % ret)
78 
79 if __name__ == "__main__":
80 
81  try:
82  # Initialize SDK resources
83  MvCamera.MV_CC_Initialize()
84 
85  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
86  print ("SDKVersion[0x%x]" % SDKVersion)
87 
88  deviceList = MV_CC_DEVICE_INFO_LIST()
89  tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
90 
91  # Enumerate devices
92  ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
93  if ret != 0:
94  print ("enum devices fail! ret[0x%x]" % ret)
95  sys.exit()
96 
97  if deviceList.nDeviceNum == 0:
98  print ("find no Device!")
99  sys.exit()
100 
101  print ("find %d devices!" % deviceList.nDeviceNum)
102 
103  for i in range(0, deviceList.nDeviceNum):
104  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
105  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE or mvcc_dev_info.nTLayerType == MV_GENTL_GIGE_DEVICE:
106  print ("\ngige device: [%d]" % i)
107  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
108  print ("device model name: %s" % strModeName)
109  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chSerialNumber)
110  print("device serial number: %s" % strSerialNumber)
111  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
112  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
113  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
114  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
115  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
116  elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
117  print ("\nu3v device: [%d]" % i)
118  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName)
119  print ("device model name: %s" % strModeName)
120 
121  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber)
122  print ("device serial number: %s" % strSerialNumber)
123 
124  nConnectionNum = input_func("please input the number of the device to connect:")
125 
126  if int(nConnectionNum) >= deviceList.nDeviceNum:
127  print ("intput error!")
128  sys.exit()
129 
130  # Create the camera instance
131  cam = MvCamera()
132 
133  # Select a device, and create a handle
134  stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
135 
136  ret = cam.MV_CC_CreateHandle(stDeviceList)
137  if ret != 0:
138  raise Exception ("create handle fail! ret[0x%x]" % ret)
139 
140  # Turn on the device
141  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
142  if ret != 0:
143  raise Exception ("open device fail! ret[0x%x]" % ret)
144 
145  # Read mode
146  print ("read to file.")
147  print('press Enter key to start.')
148  input_func()
149 
150  try:
151  hReadThreadHandle = threading.Thread(target=file_access_thread, args=(cam, 1))
152  hReadThreadHandle.start()
153  time.sleep(0.005)
154  hProgress1ThreadHandle = threading.Thread(target=progress_thread, args=(cam, 1))
155  hProgress1ThreadHandle.start()
156  except:
157  raise Exception ("error: unable to start thread")
158 
159  print ("waiting.")
160  input_func()
161 
162  hReadThreadHandle.join()
163  hProgress1ThreadHandle.join()
164 
165  # Write mode
166  print ("write from file.")
167  print('press Enter key to start.')
168  input_func()
169 
170  try:
171  hWriteThreadHandle = threading.Thread(target=file_access_thread, args=(cam, 2))
172  hWriteThreadHandle.start()
173  time.sleep(0.005)
174  hProgress2ThreadHandle = threading.Thread(target=progress_thread, args=(cam, 2))
175  hProgress2ThreadHandle.start()
176  except:
177  raise Exception ("error: unable to start thread")
178 
179  print ("waiting.")
180  input_func()
181 
182  hWriteThreadHandle.join()
183  hProgress2ThreadHandle.join()
184 
185  # Turn off the device
186  ret = cam.MV_CC_CloseDevice()
187  if ret != 0:
188  raise Exception ("close deivce fail! ret[0x%x]" % ret)
189 
190 
191  # Destroy the handle
192  ret = cam.MV_CC_DestroyHandle()
193 
194  except Exception as e:
195  print(e)
196  cam.MV_CC_CloseDevice()
197  cam.MV_CC_DestroyHandle()
198  finally:
199  # Release SDK resources
200  MvCamera.MV_CC_Finalize()